#include "SaveState.h"
#include "Game.h"
#include "BitmapFont.h"
#include "MainMenuState.h"
#include "../SGD Wrappers/SGD_InputManager.h"
#include "GameplayState.h"

SaveState* SaveState::GetInstance()
{
	static SaveState s_Instace;

	return &s_Instace;
}

void SaveState::Enter()
{
	m_nCursor = 0;
	m_fTimer = 0;
}

void SaveState::Exit()
{

}

void SaveState::Update(float dt)
{
	m_fTimer += dt;
}

void SaveState::Render()
{
	Game::Save* save = Game::GetInstance()->GetSave();


	BitmapFont temp;
	temp.Initialize();

	for (unsigned char i = 0; i < 3; i++)
	{
		if (m_nCursor == i)
			temp.Draw(save->Time[i], 32 * 2, 100 + i* 60, 0.60f, SGD::Color(255,255,0));
		else
			temp.Draw(save->Time[i], 32 * 2, 100 + i * 60, 0.50f, SGD::Color());
	}

}

bool SaveState::Input()
{
	SGD::InputManager* input = SGD::InputManager::GetInstance();
	SGD::Vector vcontroller;

	Game::Save* save = Game::GetInstance()->GetSave();

	if (m_fTimer > 0.15f)
	{
		vcontroller = input->GetLeftJoystick(0);
		m_fTimer = 0.f;
	}

	// Return to main menu
	if (input->IsKeyPressed(SGD::Key::Escape)
		|| input->IsButtonDown(0, 1))
		Game::GetInstance()->ChangeState(MainMenuState::GetInstance());

	// Delete previous data
	if (input->IsKeyPressed(SGD::Key::D)
		|| input->IsButtonPressed(0, 2))
	{
		int parse = save->Time[save->SavedSlot]->find_first_of(L' ');

		save->Time[m_nCursor]->erase(save->Time[m_nCursor]->begin() + parse + 2, save->Time[m_nCursor]->end());
		save->Upgrades[m_nCursor] = 0;
	}


	if (input->IsKeyPressed(SGD::Key::S)
		|| input->IsKeyPressed(SGD::Key::DownArrow)
		|| vcontroller.y > 0.2f)
	{
		++m_nCursor;

		// Stop at the bottom
		if (m_nCursor > 2)
			m_nCursor = 2;
	}

	if (input->IsKeyPressed(SGD::Key::W)
		|| input->IsKeyPressed(SGD::Key::UpArrow)
		|| vcontroller.y < -0.2f)
	{
		--m_nCursor;

		// Stop at top
		if (m_nCursor < 0)
			m_nCursor = 0;
	}

	// Esc sets cursor to exit
	if (input->IsKeyPressed(SGD::Key::Escape)
		|| input->IsButtonPressed(0, 1))
		m_nCursor = 2;


	if (input->IsKeyPressed(SGD::Key::Enter) || input->IsButtonPressed(0, 0))
	{
		save->SavedSlot = m_nCursor;
		Game::GetInstance()->ChangeState(GameplayState::GetInstance());
	}


	return true;
}